package cn.cqie.frame.interceptor;


import cn.cqie.frame.dto.UserContext;
import cn.cqie.frame.service.SysUserService;
import cn.cqie.frame.utils.SpringUtils;
import cn.cqie.frame.utils.TokenUtil;
import cn.cqie.frame.vo.UserVo;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xieyihong
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    public static final String HEADER_TOKEN_KEY = "token";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        log.info("requestURI-->{}", requestURI);
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
        String token = request.getHeader(HEADER_TOKEN_KEY);
        // 获取请求头
        // 请求头不为空进行解析
        if (StringUtils.isNotBlank(token)) {
            Long userId = TokenUtil.verify(token);
            if (userId == null) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录,请登录");
                return false;
            }
            UserVo userInfo = SpringUtils.getBean(SysUserService.class).getInfoById(userId);
            if (StringUtils.isBlank(userInfo.getToken())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录,请登录");
                return false;
            }
            UserContext.set(userInfo);
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未登录,请登录");
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.remove();
    }


    private void initUserContext(String token) {
        Long userId = TokenUtil.verify(token);
        UserVo userInfo = SpringUtils.getBean(SysUserService.class).getInfoById(userId);
        UserContext.set(userInfo);
    }
}